//
//  QCComposeTextView.swift
//  SwiftDemoWithSina
//
//  Created by qu on 2017/2/9.
//  Copyright © 2017年 Apple. All rights reserved.
//

import UIKit

class QCComposeTextView: UITextView {
    
//    var placeholdLabel:UILabel{
//       
//        didSet{
//            placeholderLabel = placeholdLabel
//        }
//        
//    }
    
    var placeholder:String?{
        didSet{
            
            placeholderLabel.text = placeholder
        }
    }
    //重写font属性 在didSet中监听它设置多大
    override var font: UIFont? {
        didSet{
            placeholderLabel.font = font
        }
    }

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        backgroundColor = UIColor.white
        addSubview(placeholderLabel)
        
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.left, multiplier: 1, constant: 5))
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 8))
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.width, multiplier: 1, constant: -10))
        //通过监听系统通知来监听 textView文字的改变
        
        NotificationCenter.default.addObserver(self, selector: #selector(textChange), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
    }
    
    func textChange(){
        
        placeholderLabel.isHidden = self.hasText
        
    }
    
    //懒加载占位文字
   private  lazy var placeholderLabel: UILabel = {
        let lab = UILabel()
        lab.textColor = UIColor.darkGray
        lab.numberOfLines = 0
        return lab
    }()

}
